import UIKit
import swiftScan

enum ScanType {
    case qrCode
    case barCode
    case all
}

class ScanManager {
    static let shared = ScanManager()
    private init() {}
    
    private var resultHandler: ((String) -> Void)?
    private var cancelHandler: (() -> Void)?
    
    func createScanViewController(
        type: ScanType = .all,
        result: @escaping (String) -> Void,
        cancel: @escaping () -> Void
    ) -> UIViewController {
        self.resultHandler = result
        self.cancelHandler = cancel
        
        // 1. Create scan view controller
        let scanVC = LBXScanViewController()
        
        // 2. Configure scan style
        var scanStyle = LBXScanViewStyle()
        scanStyle.animationImage = UIImage(named: "qrcode_scan_light_green")
        scanStyle.photoframeLineW = 4
        scanStyle.photoframeAngleW = 24
        scanStyle.photoframeAngleH = 24
        scanStyle.colorAngle = UIColor(red: 0.0, green: 0.8, blue: 0.0, alpha: 1.0)
        scanStyle.color_NotRecoginitonArea = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
        scanStyle.anmiationStyle = .LineMove   // Or .netGrid, .lineStill
        
        // Set scan style
        scanVC.scanStyle = scanStyle
        
        // 3. Configure scan type
//        switch type {
//        case .qrCode:
//            scanVC.scanStyle?.anmiationStyle = .LineMove
//        case .barCode:
//            scanVC.scanStyle?.anmiationStyle = .LineStill
//        case .all:
//            scanVC.scanType = .lin
//        }
//        
        // 4. Set delegate
        scanVC.scanResultDelegate = self
        
        // 5. Configure navigation
        scanVC.title = "Scan"
        scanVC.navigationItem.leftBarButtonItem = UIBarButtonItem(
            barButtonSystemItem: .cancel,
            target: self,
            action: #selector(cancelScan)
        )
        
        return scanVC
    }
    
    @objc private func cancelScan() {
        cancelHandler?()
    }
    
    func recognizeFromImage(_ image: UIImage, completion: @escaping (String?) -> Void) {
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil,
                                options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
        
        if let ciImage = CIImage(image: image),
           let features = detector?.features(in: ciImage),
           let firstFeature = features.first as? CIQRCodeFeature {
            completion(firstFeature.messageString)
        } else {
            completion(nil)
        }
    }
}

extension ScanManager: LBXScanViewControllerDelegate {
    func scanFinished(scanViewController: LBXScanViewController, scanResult: LBXScanResult?, error: Error?) {
        if let result = scanResult?.strScanned {
            resultHandler?(result)
        } else if let error = error {
            print("Scan error: \(error.localizedDescription)")
        }
    }
    
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        if let error = error {
            print("Scan error: \(error)")
        } else {
            resultHandler?(scanResult.strScanned ?? "")
        }
    }
}
